﻿using System;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
using System.ComponentModel.Design;

namespace UtfprLibrary.Windows.Forms {
    [ToolboxBitmap(typeof(ResourceFinder), "Resources.VSD_UtfprGroupBox.png")]
    [Designer("UtfprLibrary.Windows.Forms.ComponentModel.UtfprGroupBoxDesigner, UtfprLibrary.WindowsForms.Design")]
    public class UtfprGroupBox : UtfprGroupBoxBase {
        public UtfprGroupBox() {
            DataBindings.CollectionChanged += new CollectionChangeEventHandler(DataBindings_CollectionChanged);
        }

        #region Properties

        private UtfprRadioButton _defaultChecked;
        [Category("Behavior")]
        [Description("")]
        [TypeConverter(typeof(UtfprRadioButtonConverter))]
        public UtfprRadioButton DefaultChecked {
            get { return _defaultChecked; }
            set {
                if (value != null) {
                    _defaultChecked = value;
                    _defaultChecked.Checked = true;
                } else {                    
                    if(this.Controls.OfType<TableLayoutPanel>().Count() == 1) {
                        var radioButtons = this.Controls.OfType<TableLayoutPanel>().Single().Controls.OfType<UtfprRadioButtonBase>().ToList();
                        foreach (var r in radioButtons) {
                            r.Checked = false;
                        }
                    }

                    if (_defaultChecked != null) {
                        _defaultChecked.Checked = false;
                    }
                    _defaultChecked = null;
                }
            }
        }

        private object _valueField;
        [Category("Data")]
        [Description("")]
        [Bindable(true, BindingDirection.OneWay)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Browsable(false)]
        public object ValueField {
            get { return _valueField; }
            set { _valueField = value; }
        }

        #endregion

        #region Override

        protected override void OnCreateControl() {
            base.OnCreateControl();
            DefaultChecked = DefaultChecked;
        }

        protected override void OnControlRemoved(ControlEventArgs e) {
            if (UtfprControlBase.IsInDesignMode) {
                if (e.Control is UtfprRadioButton) {
                    e.Control.DataBindings.Clear();

                    if ((e.Control as UtfprRadioButton) == DefaultChecked) {
                        DefaultChecked = null;
                    }
                }
                base.OnControlRemoved(e);
            } else {
                base.OnControlRemoved(e);
            }
        }

        protected override void OnControlAdded(ControlEventArgs e) {
            if (UtfprControlBase.IsInDesignMode) {
                if (e.Control is UtfprRadioButton) {
                    if (DataBindings.Count != 0) {
                        object ds = DataBindings["ValueField"].DataSource;
                        string member = DataBindings["ValueField"].BindingMemberInfo.BindingMember;
                        (e.Control as UtfprRadioButton).DataBindings.Add(new Binding("ValueField", ds, member, true));
                    }
                } else if (!(e.Control is TableLayoutPanel || e.Control is UtfprCheckBoxBase)) {
                    throw new ArgumentException(
                        "Invalid control, just UtfprRadioButton, UtfprCheckBox or TableLayoutPanel are permited");
                }

                base.OnControlAdded(e);
            } else {
                base.OnControlAdded(e);
            }
        }
        
        #endregion

        #region EventHandlers

        private void DataBindings_CollectionChanged(object sender, CollectionChangeEventArgs e) {
            if (UtfprControlBase.IsInDesignMode) {
                Binding binding = e.Element as Binding;

                if (binding != null) {
                    if (binding.PropertyName == "ValueField") {

                        var radioButtons = Controls.OfType<TableLayoutPanel>().Single().Controls.OfType<UtfprRadioButton>();

                        foreach (var rb in radioButtons) {
                            if (rb.DataBindings[binding.PropertyName] != null) {
                                rb.DataBindings.Remove(rb.DataBindings[binding.PropertyName]);
                                rb.DataBindings.Add(new Binding(binding.PropertyName, binding.DataSource,
                                    binding.BindingMemberInfo.BindingMember, true));
                            } else {
                                rb.DataBindings.Add(new Binding(binding.PropertyName, binding.DataSource,
                                    binding.BindingMemberInfo.BindingMember, true));
                            }
                        }
                    }
                }
            }
        }

        #endregion           
    }

    #region DesignTime Converter
    public class UtfprRadioButtonConverter : ReferenceConverter {
        public UtfprRadioButtonConverter(Type type) : base(type) { }
        protected override bool IsValueAllowed(ITypeDescriptorContext context, object value) {
            //se for um UtfprRadioButton e estiver dentro do UtfprGroupBox
            return (value is UtfprRadioButton && (context.Instance as UtfprGroupBox).Controls.OfType<TableLayoutPanel>().Single().Controls.Contains(value as UtfprRadioButton));
        }
    }
    #endregion
}
